package com.rk.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.rk.model.Authorities;
import com.rk.model.User;
import com.rk.utility.Utility;

public class LoginService {
	
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List<User> getUserDetails(String userName){
		
		List<User> userList = null;
		Session session = sessionFactory.getCurrentSession();
		userList = session.createCriteria(userName).add(Restrictions.eq("userName", userName)).list();
		
		return userList;
		
	}
	
	@Transactional(readOnly = true)
	public List<User> getALLUserDetails(){
		
		List<User> userList = null;
		Session session = sessionFactory.getCurrentSession();
		userList = session.createCriteria(Authorities.class).list();
		System.out.println(userList +"==============user values ========================");
		
		return userList;
		
	}
	
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	public void saveUser(User user) throws Exception
	{
		try{

			Session session = sessionFactory.getCurrentSession();

			//save user 
			User dbUser = new User();
			dbUser.setUserName(user.getUserName());

			//encoding and then saving password to database,using spring encoder
			//dbUser.setPassword(Utility.encodePassword(user.getPassword()));
			dbUser.setPassword(user.getPassword());
			session.save(dbUser);

			Authorities auth = new Authorities();
			auth.setUserName(user.getUserName());
			auth.setAuthority(user.getRole());
			session.save(auth);
			


		}catch(ConstraintViolationException cve){
			cve.printStackTrace();
		}catch(Exception ex)		{
			ex.printStackTrace();
			throw ex;
		}

	}

}
